<template>
    <BasicModal v-bind="$attrs" @register="registerModal" width="100%" :showOkBtn="false" :showCancelBtn="false">
        <div style="width: 99%;height: 100%;position: relative;">
            <div style="width: 98%;height:8%; position: absolute; top: 1%;left: 1%;">
                <p style="font-size: 19px;float: left;margin-left: 5px;">距离考试结束还有：</p>
                <p v-if="formData.LabExamPaperPage.examTime == 0 || formData.LabExamPaperPage.examTime == null"
                    style="font-size: 19px;float: left;color: red;font-weight: bold">无时间限刷</p>
                <p v-else style="font-size: 19px;float: left;color: red;font-weight: bold">{{ formatTime(countdown) }}</p>
                <a-button style="float: right; margin-right: 1px;padding-bottom: 10px" type="primary"
                    preIcon="ant-design:plus-outlined" @click="handHandExam">
                    交卷
                </a-button>
            </div>
            <div style="width: 25%;height: 90%; position: absolute; top: 5%;left: 1%;">
                <a-card style="width: 100%;height: 100%;margin-bottom: 10px">
                    <!-- <p class="card-title">答题卡</p>
                <a-row :gutter="22" class="card-line" style="padding-left: 10px">
                    <a-tag type="info">未作答</a-tag>
                    <a-tag type="success">已作答</a-tag>
                </a-row> -->
                    <div>
                        <p class="card-title">单选题</p>
                        <a-row :gutter="22" class="card-line" style="padding-left: 10px">
                            <a-tag v-for="item in formData.LabExamPaperPage.radioList" :color="cardItemClass(item.answered)"
                                style="width: 27px;height: 26px; text-align: center;" @click="questionCard(item.sort)">{{
                                    item.sort + 1 }}</a-tag>
                        </a-row>
                    </div>
                    <div>
                        <p class="card-title">多选题</p>
                        <a-row :gutter="22" class="card-line" style="padding-left: 10px">
                            <a-tag v-for="item in formData.LabExamPaperPage.multiList" :color="cardItemClass(item.answered)"
                                style="width: 27px;height: 26px; text-align: center;" @click="questionCard(item.sort)">{{
                                    item.sort + 1 }}</a-tag>
                        </a-row>
                    </div>
                    <div>
                        <p class="card-title">判断题</p>
                        <a-row :gutter="22" class="card-line" style="padding-left: 10px">
                            <a-tag v-for="item in formData.LabExamPaperPage.judgeList" :color="cardItemClass(item.answered)"
                                style="width: 27px;height: 26px; text-align: center;" @click="questionCard(item.sort)">{{
                                    item.sort + 1 }}</a-tag>
                        </a-row>
                    </div>
                </a-card>
            </div>
            <div style="width: 72%;height:90%; position: absolute; top: 5%;left: 27%;">
                <a-card :title="Qcontent" style="width: 100%;height: 40%;position: absolute;">
                    <div v-if="formQuData.questionType == '单选题' || formQuData.questionType == '判断题'"
                        style="width: 100%;height: 100%;position: absolute;">
                        <a-radio-group v-model:value="radioValue">
                            <a-radio v-for="aitem in formQuData.answerList"
                                style="display:block;height:30px;line-height:30px;font-size: 15px;" :value="aitem.id">
                                {{ aitem.content }}
                            </a-radio>
                        </a-radio-group>
                    </div>

                    <div v-if="formQuData.questionType == '多选题'" style="width: 100%;height: 100%;position: absolute;">
                        <a-checkbox-group v-model:value="multiValue">
                            <a-checkbox v-for="aitem in formQuData.answerList"
                                style="display: flex;height:30px;lineHeight:30px;font-size: 15px;" :value="aitem.id">
                                {{ aitem.content }}
                            </a-checkbox>
                        </a-checkbox-group>
                    </div>
                </a-card>
                <div
                    style="width: 100%;height:30%; position: absolute;top: 40%; margin-right: 10px;display: block;justify-content:space-between;margin-right: 10px;padding: 9px 20px 9px 10px;">
                    <a-button v-if="showPrevious" type="primary" preIcon="ant-design:arrow-left-outlined"
                        @click="handPrevious()">上一题</a-button>&nbsp;&nbsp;
                    <a-button v-if="showNext" type="warning" preIcon="ant-design:arrow-right-outlined"
                        @click="handNext()">下一题</a-button>
                </div>
            </div>
        </div>
    </BasicModal>
</template>
  
<script lang="ts" setup>
import { reactive, ref, watch, onBeforeUnmount } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { queryPaper, updateQuAnswere, submitPaper} from './LabUserExam.api';
import { useMessage } from "/@/hooks/web/useMessage";

const { createConfirm } = useMessage();


const showPrevious = ref(false);
const showNext = ref(true);
const Qcontent = ref('');
const radioValue = ref('');
const multiValue = ref('');



const formData = reactive<Record<string, any>>({
    LabExamPaperPage: [],
});
const allIQutem = [];
const formQuData = reactive<Record<string, any>>({
    id: '',
    questionId: '',
    questionType: '',
    content: '',
    answered: '',
    answer: '',
    sort: '',
    score: '',
    actualScore: '',
    isRight: '',
    answerList: [],
});

function reset() {
    formQuData.id = null;
    formQuData.questionId = '';
    formQuData.questionType = '';
    formQuData.content = '';
    formQuData.answered = '';
    formQuData.answer = '';
    formQuData.sort = '';
    formQuData.actualScore = '';
    formQuData.isRight = '';
    formQuData.answerList = [];
}

//进入考试页面初始化数据
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, defaultFullscreen: true, canFullscreen: false, closable: false });
    formData.LabExamPaperPage = [];
    formData.LabExamPaperPage = await queryPaper({ examId: data.id });
    formData.LabExamPaperPage.radioList.forEach(item => {
        allIQutem.push(item);
    })
    formData.LabExamPaperPage.multiList.forEach(item => {
        allIQutem.push(item);
    })
    formData.LabExamPaperPage.judgeList.forEach(item => {
        allIQutem.push(item);
    })
    questionCard(0);
    const examTime = formData.LabExamPaperPage.examTime;
    const createTime = formData.LabExamPaperPage.createTime;
    const limitTime = formData.LabExamPaperPage.limitTime;
    const nowTime = new Date().getTime();

    if (examTime != null && examTime != 0 && examTime != "" && limitTime != null && limitTime != 0 && limitTime != "") {
        let diffInMilliseconds = new Date(limitTime).getTime() - new Date(createTime).getTime();
        let seconds = Math.floor(diffInMilliseconds / (60 * 1000));
        if (examTime > seconds) {
            countdown.value = seconds * 60;
            let diffInNowseconds = new Date(limitTime).getTime() - new Date(nowTime).getTime();
            let nowSeconds = Math.floor(diffInNowseconds / (60 * 1000));
            if (nowSeconds > 0 && (examTime - nowSeconds) > 1) {
                countdown.value = nowSeconds * 60;
            }
            startCountdown();
        } else {
            countdown.value = examTime * 60;
            startCountdown();
        }
    }
});

//当前答题
function questionCard(index) {
    handSave();
    reset();
    Object.assign(formQuData, allIQutem[index]);
    Qcontent.value = formQuData.sort + 1 + '.' + formQuData.content;
    if (formQuData.questionType == '单选题' || formQuData.questionType == '判断题') {
        radioValue.value = formQuData.answer;
    } else {
        multiValue.value = formQuData.answer;
    }
    handlshow();
}

//上一题
function handPrevious() {
    const index = formQuData.sort - 1;
    questionCard(index);

}
//下一题
function handNext() {
    const index = formQuData.sort + 1;
    questionCard(index);
}
//显示或隐藏按钮
function handlshow() {
    if (formQuData.sort == 0) {
        showPrevious.value = false;
    } else {
        showPrevious.value = true
    }
    // 最后一个索引
    const last = allIQutem.length - 1;
    if (formQuData.sort == last) {
        showNext.value = false;
    } else {
        showNext.value = true
    }
}

//保存试题答案
function handSave() {
    const radioV = radioValue.value;
    const multiV = multiValue.value;
    const params = { paperId: formData.LabExamPaperPage.id, quId: formQuData.questionId, answer: radioV ? radioV : multiV }
    // console.log(answers);
    if (radioV != '' && radioV != null) {
        updateQuAnswere(params);
        allIQutem[formQuData.sort].answer = radioV;
        allIQutem[formQuData.sort].answered = '1';
        radioValue.value = '';
    }
    if (multiV != '' && multiV != null) {
        updateQuAnswere(params);
        allIQutem[formQuData.sort].answer = multiV;
        allIQutem[formQuData.sort].answered = '1';
        multiValue.value = '';
    }
}

// 答题卡样式
function cardItemClass(answered) {
    if (answered == 1) {
        return 'success'
    } else {
        return 'default'
    }
}

function handHandExam() {
    const radioV = radioValue.value;
    const multiV = multiValue.value;
    const params = { paperId: formData.LabExamPaperPage.id, quId: formQuData.questionId, answer: radioV ? radioV : multiV }
    createConfirm({
        iconType: 'warning',
        title: '',
        content: '是否确认要交卷吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
            submitPaper(params,closeModal);
        }
    });
}




const countdown = ref(3600);
// const currentTime = ref(new Date().toLocaleTimeString());
let countdownId: ReturnType<typeof setInterval> | null = null;
// let timerId: ReturnType<typeof setInterval> | null = null;

// 格式化时间
const formatTime = (time: number): string => {
    const hours = Math.floor(time / 3600);
    const minutes = Math.floor((time % 3600) / 60);
    const seconds = time % 60;

    return `${hours.toString().padStart(2, '0')}小时${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}` + '秒';
};

// 开始倒计时
const startCountdown = (): void => {
    countdownId = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            stopCountdown();
        }
    }, 1000);
};

// 停止倒计时
const stopCountdown = (): void => {
    if (countdownId) {
        clearInterval(countdownId);
        countdownId = null;
    }
};

// 在组件销毁之前清除倒计时器
onBeforeUnmount(() => {
    stopCountdown();
});

// 监听 countdown 的变化
watch(countdown, (newValue) => {
    console.log('当前倒计时:', newValue);
});

// 开始定时器
// const startTimer = (): void => {
//     timerId = setInterval(() => {
//         currentTime.value = new Date().toLocaleTimeString();
//     }, 1000);
// };

// 停止定时器
// const stopTimer = (): void => {
//     if (timerId) {
//         clearInterval(timerId);
//         timerId = null;
//     }
// };

// 在组件销毁之前清除定时器
// onBeforeUnmount(() => {
//     stopTimer();
// });

</script>
  
<style>
/**隐藏样式-modal确定按钮 */
.jee-hidden {
    display: none !important;
}

.qu-content div {
    line-height: 30px;
    width: 100%;
}

.el-checkbox-group label,
.el-radio-group label {
    width: 100%;
}

.content-h {
    height: calc(100vh - 110px);
    overflow-y: auto;
}

.card-title {
    background: #eee;
    line-height: 35px;
    width: 100%;
    text-align: center;
    font-size: 13px;
}

.card-line {
    padding-left: 10px
}

.a-button {
    padding-left: 10px;
    /* 设置按钮之间的间隔大小 */
}

.card-line span {
    cursor: pointer;
    margin: 2px;
}

::v-deep .el-radio,
.el-checkbox {
    padding: 9px 20px 9px 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-bottom: 10px;
    width: 100%;
}

.is-checked {
    border: #409eff 1px solid;
}

.el-radio img,
.el-checkbox img {
    max-width: 200px;
    max-height: 200px;
    border: #dcdfe6 1px dotted;
}

.ant-radio-wrapper {
    width: 100%;
    height: 5%;
    padding: 9px 20px 9px 10px;
}

::v-deep .el-checkbox__inner {
    display: none;
}

::v-deep .el-radio__inner {
    display: none;
}

::v-deep .el-checkbox__label {
    line-height: 30px;
}

::v-deep .el-radio__label {
    line-height: 30px;
}
</style>
  